package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.security.auth.login.LoginException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;

    @Override
    public User login(UserLoginDTO userLoginDTO) {
  //1.通过HttpClient,构造登陆校验请求
        //构造微信小程序登陆参数
        Map map = new HashMap();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",userLoginDTO.getCode());
        map.put("grant_type","authorization_code");
//调用doGet方法
        String RES = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session",map);
        //2.解析响应结果 返回openid
        JSONObject jsonObject = JSON.parseObject(RES);
        String openid = (String) jsonObject.get("openid");
if (openid==null){
    throw new LoginFailedException(MessageConstant.USER_NOT_LOGIN);
}
        //3.判断是否为新用户，根据openid查询user表
User user =userMapper.slectUser(openid);
  //4.如果是新用户，初始化用户数据表
if (user==null){
     user = new User();
    user.setOpenid(openid);
    user.setCreateTime(LocalDateTime.now());
    user.setName(openid.substring(0,5));
    userMapper.insertUser(user);
}
  //5.否则，直接返回User对象数据
        return user;
    }
}
